<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import * as API from '@/api/index.js'

export default {
  name: 'App',
  data() {
    return {
      taskIds: [],
      candleTaskId: -1
    }
  },
  computed: {
      ...mapGetters([
        'addr',
        'board',
        'account',
        'curPrice',
        'curPaireObj'
      ])
  },
  watch: {
    curPaireObj: function(newVal) {
      this.getCandle1D()
      this.runAllTask()
    }
  },
  created(){
    const self = this
    if(window.ethereum){
      ethereum.on('accountsChanged', accounts => {
        if(accounts.length) {
          // console.log('App.vue==>>created.accountsChanged, accounts: %o',accounts)
          self.$store.dispatch('user/loginMetamask', accounts[0])
        }else{
          // console.log('App.vue==>>created.accountsChanged logout')
          self.$store.dispatch('user/loginMetamask', '')
        }
      })
    }

    this.getCandle1D()

    this.runAllTask()
  },
  methods:{
    runAllTask(){
      this.taskIds.forEach(id => {
        log('App.vue.runAllTask', {id})
        id && window.clearTimeout(id)
      })
      this.taskIds = []
      let rightNowKeyArray = {
        'updateAccount':[this.addr],
        'getSpotPrice': [],
        'getTotalMargin': [this.addr],
        'getPositionMargin': [this.addr],
        'getUnrealizedPnl': [this.addr]
      }

      for (const key in rightNowKeyArray) {
        if (Object.hasOwnProperty.call(rightNowKeyArray, key)) {
          const arg = rightNowKeyArray[key];
          this.runTask(key, arg)
        }
      }
    },
    runTask(key, arg){
      this.$store.dispatch(`user/${key}`, ...arg)
      log('App.vue.runTask', {key, arg})
      const id = setTimeout(this.runTask.bind(this, key, arg), 1000 * 5)
      this.taskIds.push(id)
    },
    getCandle1D(){
      this.candleTaskId && window.clearTimeout(this.candleTaskId)
      API.getCandles({
        instId: this.curPaireObj.instId,
        after: Date.now(), // 时间戳之前的数据
        before: '', // 时间戳之后的数据
        bar: '1D', // 时间粒度
        limit: '1'
      })
        .then(res => {
          if(res.data.length) {
            this.$store.commit('user/SET_CANDLE_1D',
              this.cleanCandleData(res.data[0].slice(1)))
          }
          this.candleTaskId = setTimeout(this.getCandle1D, 15 * 1000)
        })
        .catch(() => {
          this.candleTaskId = setTimeout(this.getCandle1D, 15 * 1000)
        })
    },
    cleanCandleData(raw){
      let val = {}
      val.open = raw[0].replace(',','')
      val.close = raw[3].replace(',','')
      val.lowest = raw[2].replace(',','')
      val.highest = raw[1].replace(',','')
      // console.log('App.vue==>>cleanCandleData, val: %o', val)
      return val
    }
  }
}
</script>
